﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NLog;
using System.Diagnostics.Contracts;
using System.IO;

namespace YasharEl.Infrastructure.Diagnostics.Logging.NLog
{
    public class NLogLoggerFactory : ILoggerFactory
    {
        #region ILoggerFactory Implementations

        public ILogger Create(Type type)
        {
            Type nLogLoggerOpenGenericType = typeof(NLogLogger<>);

            // TODO: Check that type is open generic type
            // If this open generic type or partial closed generic type CreateInstance fails.
            Type nLogLoggerClosedGenericType = nLogLoggerOpenGenericType.MakeGenericType
                (
                    new Type[] { type }
                );
            return (ILogger)Activator.CreateInstance(nLogLoggerClosedGenericType, new object[] { LogManager.GetLogger(type.FullName) });
        }

        public ILogger Create(string name)
        {
            return new NLogLogger(LogManager.GetLogger(name));
        }

        public bool InitializeLoggingFactory(string configFilename, string factoryName)
        {
            // TODO: Implement NLog as lo4net repository by factory name
            if (!Path.IsPathRooted(configFilename))
            {
                configFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, configFilename);
            }

            FileInfo configFile = new FileInfo(configFilename);

            if (!configFile.Exists)
            {
                throw new InvalidSystemConfigurationException(string.Format("Could not configure NLog component.Given file {0} not exists.", configFilename));
            }

            LogManager.Configuration = new global::NLog.Config.XmlLoggingConfiguration(configFilename);

            return true;
        }

        #endregion
    }
}
